package com.zgh.zhongcan.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.fasterxml.jackson.databind.util.BeanUtil;
import com.zgh.zhongcan.common.CustomException;
import com.zgh.zhongcan.common.R;
import com.zgh.zhongcan.dto.DishDto;
import com.zgh.zhongcan.entity.*;
import com.zgh.zhongcan.service.*;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.stream.Collectors;

/**
 * 菜品管理
 * @author 时侍
 * @version 1.0
 **/
@RestController
@RequestMapping("/dish")
public class DishController {
    @Autowired
    private DishService dishService;

    @Autowired
    private DishFlavorService dishFlavorService;

    @Autowired
    private CategoryService categoryService;
    @Autowired
    private SetmealDishService setmealDishService;
    @Autowired
    private SetmealService setmealService;

    /**
     * 新增菜品
     * @param dishDto
     * @return
     */
    @PostMapping
    public R<String> save(@RequestBody DishDto dishDto){
        dishService.saveWithFlavor(dishDto);
        return R.success("新增菜品成功");
    }

    /**
     * 菜品信息 分页查询
     * @param page
     * @param pageSize
     * @param name
     * @return
     */
    @GetMapping("/page")
    public R<Page> page(int page,int pageSize,String name){
        //构造分页构造器
        Page<Dish> pageInfo=new Page<>(page,pageSize);
        Page<DishDto> dishDtoPage=new Page<>();//分类名也要封装
        //条件构造器
        LambdaQueryWrapper<Dish> queryWrapper=new LambdaQueryWrapper<>();
        queryWrapper.like(name!=null,Dish::getName,name);//过滤条件，模糊查询
        queryWrapper.orderByDesc(Dish::getUpdateTime);//排序条件，根据更新时间逆序
        //执行分页查询
        dishService.page(pageInfo,queryWrapper);

        //对象拷贝，拷贝除records(数据)外的字段
        BeanUtils.copyProperties(pageInfo,dishDtoPage,"records");

        //获取分页的数据，将其中Dish转换为DishDto,因为我们需要分类的名称
        List<Dish> records=pageInfo.getRecords();
        //遍历records集合，创建dto对象，最终收集dto对象
        List<DishDto> list = records.stream().map((item) -> {
            DishDto dishDto = new DishDto();
            //拷贝dish的普通属性
            BeanUtils.copyProperties(item, dishDto);
            //根据id获取分类名称
            Long categoryId = item.getCategoryId();//分类id
            //根据id查询分类对象，获取分类名称
            Category category = categoryService.getById(categoryId);
            if (category!=null){
                dishDto.setCategoryName(category.getName());
            }

            return dishDto;
        }).collect(Collectors.toList());

        //将数据装入page
        dishDtoPage.setRecords(list);
        return R.success(dishDtoPage);
    }

    /**
     * 根据id查询 菜品信息 和 对应的口味信息
     * @param id
     * @return
     */
    @GetMapping("/{id}")
    public R<DishDto> get(@PathVariable Long id){
        DishDto dishDto = dishService.getByIdWithFlavor(id);
        return R.success(dishDto);
    }

    /**
     * 修改菜品
     * @param dishDto
     * @return
     */
    @PutMapping
    public R<String> update(@RequestBody DishDto dishDto){
        dishService.updateWithFlavor(dishDto);
        return R.success("修改菜品成功");
    }
    /**
     * 删除菜品
     * @param ids
     * @return
     */
    @DeleteMapping
    public R<String> delete(@RequestParam List<Long> ids){//@RequestParam注解获取请求参数
        //select count(*) from setmeal where id in (1,2,3) and status = 1
        //查询套餐状态，确定是否可用删除，只有停售才可删除
        LambdaQueryWrapper<Dish> queryWrapper = new LambdaQueryWrapper();
        queryWrapper.in(Dish::getId,ids);
        queryWrapper.eq(Dish::getStatus,1);

        int count = dishService.count(queryWrapper);
        if(count > 0){//存在售卖中菜品
            //如果不能删除，抛出一个业务异常
            throw new CustomException("菜品正在售卖中，不能删除");
        }
        //先删除关系表，setmeal_dish，要判断关联的套餐是否停售
        LambdaQueryWrapper<SetmealDish> queryWrapper2 = new LambdaQueryWrapper();
        queryWrapper2.eq(SetmealDish::getDishId,ids);
        setmealDishService.count(queryWrapper2);
        if(count > 0){//存在售卖中套餐
            //如果不能删除，抛出一个业务异常
            throw new CustomException("需要先删除套餐");
        }
        //setmealService.removeWithDish(ids2);

        //如果可以删除，先删除菜品表中的数据---dish
        dishService.removeByIds(ids);

        //delete from setmeal_dish where setmeal_id in (1,2,3)
        //没有setmeal_dish的主键id，只能用setmeal套餐id来删除
        LambdaQueryWrapper<DishFlavor> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.in(DishFlavor::getDishId,ids);
        //删除关系表中的数据----dish_flavor
        dishFlavorService.remove(lambdaQueryWrapper);


        return R.success("菜品删除成功");
    }

    /**
     * 停售起售功能
     * @param status 要修改成的状态
     * @param ids
     * @return
     */
    @PostMapping("/status/{status}")
    public R<String> status(@PathVariable int status,@RequestParam List<Long> ids){
        /*//根据dish的id查出菜品
        LambdaQueryWrapper<Dish> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.in(ids!=null,Dish::getId,ids);
        List<Dish> dishList = dishService.list(queryWrapper);
        //修改查出菜品的状态
        dishList.stream().forEach((item) -> {
             item.setStatus(status);
        });
        dishService.updateBatchById(dishList);//批量操作*/
        UpdateWrapper<Dish> updateWrapper = new UpdateWrapper();
        updateWrapper.lambda().in(ids!=null,Dish::getId,ids);
        updateWrapper.lambda().set(Dish::getStatus,status);
        dishService.update(updateWrapper);
        return R.success("修改成功");
    }

    /**
     * 根据条件查询对应菜品的数据,以及前台需要展示菜品对应的口味信息
     * @param dish
     * @return
     */
    @GetMapping("/list")
    public R<List<DishDto>> list(Dish dish){
        //根据分类id查对应的菜品集合
        LambdaQueryWrapper<Dish> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(dish.getCategoryId() != null,Dish::getCategoryId,dish.getCategoryId());
        queryWrapper.orderByAsc(Dish::getSort).orderByDesc(Dish::getUpdateTime);
        //可选，查询起售状态状态的菜品
        queryWrapper.eq(Dish::getStatus,1);

        List<Dish> list = dishService.list(queryWrapper);

        //通过分类id填充分类名 通过菜品id查口味表，填充口味
        List<DishDto> dishDtoList = list.stream().map((item) -> {
            DishDto dishDto = new DishDto();
            //拷贝dish的普通属性
            BeanUtils.copyProperties(item, dishDto);
            //根据id获取分类名称
            Long categoryId = item.getCategoryId();//分类id
            //根据id查询分类对象，获取分类名称
            Category category = categoryService.getById(categoryId);
            if (category!=null){
                dishDto.setCategoryName(category.getName());
            }

            //通过菜品id查口味
            Long dishId = item.getId();
            LambdaQueryWrapper<DishFlavor> lambdaQueryWrapper=new LambdaQueryWrapper<>();
            lambdaQueryWrapper.eq(DishFlavor::getDishId,dishId);
            List<DishFlavor> dishFlavorList = dishFlavorService.list(lambdaQueryWrapper);
            dishDto.setFlavors(dishFlavorList);
            return dishDto;
        }).collect(Collectors.toList());

        return R.success(dishDtoList);

    }

}
